import 'package:flutter/material.dart';
import 'package:mi_mang_flutter/model/public/type_model.dart';
import 'package:mi_mang_flutter/res/styles.dart';
import 'package:mi_mang_flutter/routers/fluro_navigator.dart';
import 'package:mi_mang_flutter/utils/dialog_util.dart';
import 'base_dialog.dart';

class WidgetTypeDialog extends StatefulWidget {
  WidgetTypeDialog({
    Key? key,
    this.title,
    this.selectItem,
    required this.items,
    this.hiddenButton = false,
    required this.onPressed,
  }) : super(key: key);

  final String? title;
  final TypeModel? selectItem;
  final List<TypeModel> items;
  final Function(TypeModel?) onPressed;
  final bool hiddenButton;
  final bool isBottomLine = false;
  final double itemHeight = 42.0;

  @override
  _WidgetTypeDialog createState() => _WidgetTypeDialog();
}

class _WidgetTypeDialog extends State<WidgetTypeDialog> {
  TypeModel? _selectItem;
  late List<TypeModel> _items;
  @override
  void initState() {
    super.initState();
    _selectItem = widget.selectItem;
    _items = widget.items;
  }

  List<Widget> _getListItem() {
    return _items.map(
      (item) {
        return Material(
          type: MaterialType.transparency,
          child: InkWell(
            child: _getItem(item),
            onTap: () {
              if (mounted) {
                setState(() {
                  _selectItem = item;
                  if (widget.hiddenButton) {
                    NavigatorUtils.goBack(context);
                    widget.onPressed(_selectItem);
                  }
                });
              }
            },
          ),
        );
      },
    ).toList();
  }

  Widget _getItem(TypeModel item) {
    return ListTile(
      title: Text(
        item.name!,
        style: TextStyles.titleMedium,
      ),
      selected: _selectItem?.value == item.value,
      trailing: Icon(_selectItem?.value == item.value
          ? Icons.radio_button_checked
          : Icons.radio_button_unchecked),
    );
  }

  @override
  Widget build(BuildContext context) {
    return BaseDialog(
      title: widget.title,
      width: 270.0,
      hiddenButton: widget.hiddenButton,
      child: Container(
        constraints: BoxConstraints(minHeight: 50.0, maxHeight: 250.0),
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            mainAxisSize: MainAxisSize.min,
            children: ListTile.divideTiles(
              context: context,
              tiles: _getListItem(),
            ).toList(),
          ),
        ),
      ),
      onPressed: () {
        NavigatorUtils.goBack(context);
        widget.onPressed(_selectItem);
      },
    );
  }

  @override
  void dispose() {
    DialogUtil.isShowDialog = false;
    super.dispose();
  }
}
